package com.xander.qqdatabase.exception;

import com.xander.qqdatabase.base.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * 全局异常拦截器
 * @author 叶振东
 * @date 2019-01-10
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    /**
     * 拦截服务器内部异常
     * @param e
     * @param body
     * @param headers
     * @param status
     * @param request
     * @return org.springframework.http.ResponseEntity<java.lang.Object>
     * @author yezhendong
     * @date 2019-01-14
     */
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception e, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        log.warn(e.getMessage(), e);
        return super.handleExceptionInternal(e, body, headers, status, request);
    }

    /**
     * 拦截自定义业务异常并返回Json
     * @param e
     * @return org.springframework.http.ResponseEntity<java.lang.Object>
     * @author yezhendong
     * @date 2019-01-14
     */
    @ExceptionHandler
    public ResponseEntity<Object> handleBusinessException(BusinessException e) {
        log.warn(e.getSnapshot(), e);
        return new ResponseEntity<>(new ResultBean(e.getCode(), e.getMessage()), HttpStatus.OK);
    }

    @ExceptionHandler
    public ResponseEntity<Object> handleRuntimeException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler
    public ResponseEntity<Object> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}